import type { ActionType, TodoItem } from './todos'

const reducer = function (state: TodoItem[], action: ActionType) {
  switch (action.type) {
    // 添加任务
    case 'add':
      const ids = state.map((item) => item.id)
      let id = Math.max.apply(null, ids) + 1

      if (ids.length === 0) {
        id = 1
      }

      return [
        ...state,
        {
          id,
          text: action.payload,
          done: false
        }
      ]

    // 删除任务
    case 'delete':
      return state.filter((todo) => todo.id !== action.payload)

    // 切换任务
    case 'toggle':
      return state.map((todo) => {
        if (todo.id === action.payload) {
          return {
            ...todo,
            done: !todo.done
          }
        }

        return todo
      })

    case 'loadData':
      return action.payload

    default:
      return state
  }
}

export default reducer
